package com.mall.system.server.controller;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.mall.cart.common.domain.Cart;
import com.mall.cart.remote.CartRemoteServer;
import com.mall.common.core.domain.Result;
import com.mall.common.core.utils.sign.Base64;
import com.mall.common.redis.service.RedisService;
import com.mall.common.security.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
public class AliPayController {

    private final Config aliPayConfig;

    @Autowired
    private RedisService redisService;
    @Autowired
    private CartRemoteServer cartRemoteServer;


    @GetMapping("/pay/{skuIdsString}")
    public Result pay(@PathVariable("skuIdsString") String skuIdsString) throws Exception {
        Long userid = SecurityUtils.getLoginUser().getUserid();
        //先获取这些商品的总金额
        String[] skuIds = skuIdsString.split(",");
        List<Cart> cartList = cartRemoteServer.findCartList().getData();
        String skuName = cartList.stream()
                .flatMap(cart -> cart.getCartItemPoList().stream()) // Flatten the List<CartItem>
                .filter(cartItem -> Arrays.asList(skuIds).contains(String.valueOf(cartItem.getSkuId()))) // Filter items by SKU IDs
                .map(cartItem -> cartItem.getSkuTitle()) // Extract the price as double
                .collect(Collectors.joining(","));
        // 规范化字符串中的空格：将多个连续空格替换为单个空格
        skuName = skuName.replaceAll("\\s+", " ");

        //如果字符串长度超过10个字符，截断并加上省略号
        if (skuName.length() > 10) {
            skuName = skuName.substring(0,6).replaceAll("\\s+$", "") + "..."; // 截断并去除结尾可能存在的多余空格后加省略号
        }

        //商品总金额
        Double sumPrice = cartList.stream()
                .flatMap(cart -> cart.getCartItemPoList().stream())
                .filter(cartItem -> Arrays.asList(skuIds).contains(String.valueOf(cartItem.getSkuId())))
                .map(cartItem -> cartItem.getCartItemPrice().doubleValue())
                .reduce(0.0, Double::sum);

        //创建订单号
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义格式：年月日时分
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
        // 格式化当前时间为指定格式的字符串
        String formattedNow = now.format(formatter);
        formattedNow=formattedNow+""+userid;

        Factory.setOptions(aliPayConfig);

        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(skuName, formattedNow, String.valueOf(sumPrice));



        JSONObject httpBodyJsonObject = JSONObject.parseObject(JSON.parseObject(response.getHttpBody()).toString());
        String qrCode = httpBodyJsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");

        QrConfig qrConfig = new QrConfig(400,400);
        BufferedImage bufferedImage = QrCodeUtil.generate(qrCode, qrConfig);

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage,"jpg",os);
        }catch (IOException e){
            return Result.error(e.getMessage());
        }

        System.out.println(Base64.encode(os.toByteArray()));
        return Result.success(Base64.encode(os.toByteArray()));
    }


    @PostMapping("/notify")
    public Result notifyPay(HttpServletRequest request){

        System.out.println(request.toString());

        System.out.println("支付成功");
        return Result.success();
    }



    @GetMapping("/payByCart")
    public Result payByCart(){

        return Result.success();
    }

}
